package com.bing.beike.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.bing.beike.common.result.CommonResult;
import com.bing.beike.entity.User;
import com.bing.beike.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理接口", description = "用户相关的增删改查操作")  // 接口分组标签
public class UserController {

    @Autowired
    public UserService userService;


    @PostMapping("register")
    @Operation(summary = "创建用户", description = "提交用户信息并保存")
    public CommonResult<User> createUser(@RequestBody User user) {
        int result = userService.register(user);
        try {
            if (result == 1) {
                return CommonResult.success(user);
            }else {
                return CommonResult.error(500, "创建用户失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error(500, "异常错误");
        }
    }

    @GetMapping("/{username}")
    @Operation(summary = "获取用户信息", description = "根据用户名获取用户信息")
    public CommonResult<User> getUser(@PathVariable String username) {
        User user = userService.findByUsername(username);
        try {
            if (user != null) {
                return CommonResult.success(user);
            }
        }catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error(500, "获取用户信息失败");
        }
        return CommonResult.error(404, "用户不存在");
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "提交用户名和密码进行登录")
    public CommonResult<String> login(@RequestBody User user) {
        User loginUser = userService.login(user);
        try {
            if (loginUser != null) {
                StpUtil.login(user.getUsername()); // 参数为用户ID
                String token =  StpUtil.getTokenValue();
                System.out.println(token);
//                token = token.replace("Bearer ", "");
                return CommonResult.success(token);
            }
        }catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error(500, "登录失败");
        }
        return CommonResult.error(401, "用户名或密码错误");
    }

    @PostMapping("/logout")
    @Operation(summary = "用户登出", description = "登出当前登录用户")
    public CommonResult<String> logout() {
//        String username = StpUtil.getTokenValue();
//        System.out.println(username);
        StpUtil.logout(); // Sa-Token 会自动踢出当前用户
        return CommonResult.success("登出成功");
    }
}